package com.jungle.sp.daily.config;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 86189
 */
@Configuration
public class VirtualThreadPoolConfig {

    private static final TransmittableThreadLocal<String> CONTEXT = new TransmittableThreadLocal<>();

    @Bean(destroyMethod = "shutdownNow")
    public ExecutorService virtualThreadPool() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    public void executeWithContext(String context, ExecutorService executor) {
        CONTEXT.set(context);

        // 包装任务
        Runnable task = TtlRunnable.get(() -> {
            try {
                // 在虚拟线程中执行任务
                String contextValue = CONTEXT.get();
                System.out.println("ThreadLocal Value in Virtual Thread: " + contextValue);
            } finally {
                // 确保任务执行后清理上下文
                CONTEXT.remove();
            }
        });

        executor.execute(task);
    }
}
